package com.example.bank.service.image;

import cn.hutool.core.util.StrUtil;
import com.example.bank.dao.ImageDao;
import com.example.bank.exception.SystemException;
import com.example.bank.pojo.Image;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：Leeziqiang
 * @description：TODO
 * @date ：2021/12/18 20:23
 */
@Service
@Transactional
public class ImageServiceImpl implements ImageService {

    private static final Logger logger = LoggerFactory.getLogger(ImageServiceImpl.class);

    @Autowired
    private ImageDao imageDao;

    @Override
    public boolean addImage(String clientIdNumber, String name, String path, String type) {
        Image image = new Image();
        image.setClientIdNumber(clientIdNumber);
        image.setName(name);
        image.setPath(path);
        image.setType(type);
        int n = imageDao.saveImage(image);
        if (n > 0) {
            return true;
        }
        return false;
    }

    @Override
    public Map<String, List<String>> listImages(String clientIdNumber){
        // 根据客户id和类型查找
        Map<String, List<String>> images = new LinkedHashMap<String, List<String>>();
        String[] types = new String[]{"hukouben", "shenfenzheng", "jiehunzheng", "zhengxin", "fangchanzheng", "xingshizheng", "cheliangdazhao", "buchongcailiao"};
        for (String type : types) {
            List<String> paths = imageDao.findPath(clientIdNumber, type);
            images.put(type, paths);
        }
        return images;
    }



    @Override
    public Map<String, List<String>> listNames(String clientIdNumber) throws Exception {
        Map<String, List<String>> images = new LinkedHashMap<String, List<String>>();
        String[] types = new String[]{"hukouben", "shenfenzheng", "jiehunzheng", "zhengxin", "fangchanzheng", "xingshizheng", "cheliangdazhao", "buchongcailiao"};
        for (String type : types) {
            List<String> names = imageDao.findName(clientIdNumber, type);
            images.put(type, names);
        }
        return images;
    }

    @Override
    public List<String> listByNumber(String number) {
        return imageDao.listByNumber(number);
    }

    @Override
    public boolean deleteByPath(String path) {
        if (StrUtil.isEmpty(path)) {
            throw new SystemException("图片path为空");
        }
        String imageName = imageDao.findNameByPath(path);
        File file = new File(imageName);
        file.delete();
        int n = imageDao.deleteByPath(path);
        if (n > 0) {
            return true;
        }
        return false;
    }
}
